package com.nlelpct.system.config;

import lombok.extern.slf4j.Slf4j;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * @author :小马
 * @date : 2023-07-11
 */
@Slf4j
public class RetryInterceptor implements Interceptor {

    private int retryNum = 3;

    @Override
    public Response intercept(Chain chain) {
        Request request = chain.request();
        int currentTimes = 0;
        Response response = null;
        while (currentTimes < retryNum) {
            try {
                response = chain.proceed(request);
                if (response.isSuccessful()) {
                    break;
                } else {
                    log.error("服务器响应异常: response:[{}] request:[{}]",
                            response.toString(), request.toString());
                    response.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException("网络异常");
            } finally {
                currentTimes++;
            }
        }
        return response;
    }
}
